﻿using UniRx;
using UnityEngine;

public class PlayerExp : MonoBehaviour
{
    private int _exp = 0;
    private int _expTotal = 0;
    private int _level = 0;

    private void Start()
    {
        RxEventBus.Publish(new PlayerExpChangeEvent(_exp, GetCurrentLevelUpExp(), _expTotal, _level));
    }

    private int GetCurrentLevelUpExp()
    {
        // 获取当前等级升级所需经验
        return Mathf.RoundToInt(100.0f * (_level + 1) * ((_level + 1) / 10f));
        ;
    }

    private void AddExp(int exp)
    {
        _exp += exp;
        _expTotal += exp;
        while (_exp >= GetCurrentLevelUpExp())
        {
            _exp -= GetCurrentLevelUpExp();
            _level++;
        }

        RxEventBus.Publish(new PlayerExpChangeEvent(_exp, GetCurrentLevelUpExp(), _expTotal, _level));
    }

    private void OnEnable()
    {
        //监听enemy死亡
        RxEventBus.Subscribe<EnemyDead>().Subscribe(e =>
        {
            {
                AddExp(e.exp);
            }
        }).AddTo(this);
    }

    private void OnDisable()
    {
        //监听enemy死亡
        RxEventBus.Unsubscribe<EnemyDead>();
    }
}